from django.db import models
from DjangoUeditor.models import UEditorField
from django.contrib.auth.models import User
from django.utils import timezone
from django.shortcuts import reverse
from django.template.defaultfilters import strip_tags


# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=20, verbose_name='文章分类')

    class Meta:
        verbose_name = "文章分类"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Tags(models.Model):
    name = models.CharField(max_length=20, verbose_name='文章标签')

    class Meta:
        verbose_name = '标签'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Blog(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    title = models.CharField(max_length=100, verbose_name='文章标题')
    body = UEditorField(verbose_name="文章详情", width=800, height=500, imagePath='body_image')
    desc = models.CharField(max_length=50, verbose_name='文章摘要', blank=True)
    created = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    image = models.ImageField(upload_to="blog/%Y/%m", verbose_name="封面图", max_length=100)
    tag = models.ForeignKey('blog.Tags', on_delete=models.CASCADE, verbose_name='文章标签')
    category = models.ForeignKey('blog.Category', on_delete=models.CASCADE,
                                 verbose_name='文章所属分类')
    is_recommend = models.BooleanField(default=False, verbose_name="是否推荐")
    total_views = models.PositiveIntegerField(default=0, verbose_name='浏览数')

    class Meta:
        # ordering 指定模型返回的数据的排列顺序
        # '-created' 表明数据应该以倒序排列
        ordering = ('-created',)
        verbose_name = '博客'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:detail', kwargs={'id': self.id})

    def increase_views(self):
        self.total_views += 1
        self.save(update_fields=['total_views'])

    def save(self, *args, **kwargs):
        self.desc = strip_tags(self.body)[:50]
        super().save(*args, **kwargs)


class Contact(models.Model):
    email = models.CharField(max_length=20, verbose_name='电子邮件')
    qq = models.CharField(max_length=20, verbose_name='QQ')
    introduce = models.CharField(max_length=100, verbose_name='自我介绍')
    we_chat = models.ImageField(upload_to="contact/%Y/%m", verbose_name="微信图片", max_length=100)

    class Meta:
        verbose_name = '联系我们'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.introduce
